package org.neu.onlineparadise.Interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.neu.onlineparadise.utils.JWTutil;
import org.neu.onlineparadise.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception{
        //在请求头中获取名为Authorization的token令牌
        String token=request.getHeader("Authorization");
        try {
            ValueOperations<String,String> op=stringRedisTemplate.opsForValue();

            //在redis缓存中匹配token
            String redisToken=op.get(token);
            if(redisToken==null){//失效
                throw new RuntimeException();
            }

            //存入ThreadLocal
            Map<String,Object> claims= JWTutil.checkToken(token);
            ThreadLocalUtil.set(claims);

            return true;


        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    //后置清除
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
